package com.peaker.advertisingpro.utils

import android.content.Context
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.*

/**
 *  @ 作者 CODE_LYF
 *  @ 时间   2021/4/24.
 *  代码人生
 */
object FileUtils {
    /**
     * 获取文件中json
     *
     */
    fun getJsonFromFile(filePath: String): String {
        val sb = StringBuilder()
        if (filePath.isNullOrEmpty()) {
            return ""
        }
        try {
            var fileInputStream = FileInputStream(File(filePath))
            if (fileInputStream != null) {
                val inputStreamReader = InputStreamReader(fileInputStream)
                val bufferedReader = BufferedReader(inputStreamReader)
                var line: String? = ""
                while (bufferedReader.readLine().also { line = it } != null) {
                    sb.append(line)
                }
                fileInputStream.close()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return sb.toString().trim()
    }

    fun getJson(
        mContext: Context,
        fileName: String?
    ): String? {
        val sb = java.lang.StringBuilder()
        val am = mContext.assets
        try {
            val br = BufferedReader(
                InputStreamReader(
                    am.open(fileName)
                )
            )
            var next: String? = ""
            while (null != br.readLine().also { next = it }) {
                sb.append(next)
            }
            br.close()
        } catch (e: IOException) {
            e.printStackTrace()
            sb.delete(0, sb.length)
        }
        return sb.toString().trim { it <= ' ' }
    }

    /**
     * 将数据写入文件
     * @param filePath String  文件地址
     * @param str String 写入内容
     */
     fun writeFile(filePath: String, str: String, fun1: () -> Unit) {
        GlobalScope.launch {
//        var file = File("/storage/emulated/0/DCIM/a.json")
            var file = File(filePath)
            val fileOutputStream = FileOutputStream(file) //实例化FileOutputStream
            val outputStreamWriter = OutputStreamWriter(fileOutputStream, "utf-8") //将字符流转换为字节流
            val bufferedWriter = BufferedWriter(outputStreamWriter) //创建字符缓冲输出流对象
            bufferedWriter.write(str)//将格式化的jsonarray字符串写入文件
            bufferedWriter.flush()//清空缓冲区，强制输出数据
            bufferedWriter.close()//关闭输出流
            withContext(Dispatchers.Main) {
                fun1()
            }
        }
    }
}